<template>
  <div
    ref="echart"
    v-element-size="onRize"
    class="w-full h-full overflow-hidden"
  ></div>
</template>
<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref, useTemplateRef, watch } from 'vue';
import { vElementSize } from '@vueuse/components';
import type { ISpec } from '@visactor/vchart';
import VChart from '@visactor/vchart';
import { useAppStore } from '@/stores';
defineOptions({
  name: 'EchartComponent',
});

const props = withDefaults(defineProps<{ options: ISpec }>(), {});

const el = useTemplateRef('echart');
const chart = ref<VChart | null>(null);

const onRize = () => {
  if (chart.value) {
    chart.value.reLayout();
  }
};

const render = () => {
  if (el.value) {
    const options = props.options;
    chart.value = new VChart(options, {
      dom: el.value,
    });
    chart.value.renderSync();
  }
};

const unWatchUpdateSpec = watch(
  () => props.options,
  () => {
    if (chart.value) {
      chart.value.updateSpec(props.options);
    }
  },
  {
    deep: true,
  },
);

const appStore = useAppStore();
const unWatch = watch(
  () => appStore.theme,
  () => {
    VChart.ThemeManager.setCurrentTheme(
      appStore.theme == 'dark' ? 'legacyDark' : 'legacyLight',
    );
  },
  {
    immediate: true,
  },
);

onMounted(() => {
  render();
});

onBeforeUnmount(() => {
  console.log('onBeforeMount');
  unWatchUpdateSpec();
  unWatch();

  if (chart.value) {
    chart.value.release();
  }
});
</script>
